<!--suppress ALL -->
<template>
  <l-content :app="app" width="1500px" v-loading="loading" no-padding no-breadcrumb>
    <el-form inline label-width="140px" size="mini" ref="form" :rules="rules" :model="form">
      <el-card class="card-bottom-spacing">
        <div slot="header" class="card-title">
          平台信息
          <el-button type="primary" size="mini" @click="onImport" style="margin-left: 10px"><i class="fa fa-cloud-download"></i> 根据PNR导入</el-button>
        </div>
        <div class="msg-bg-cyan">
          <!--
            <el-form-item label="状态">
              <span style="display: inline-block;font-size: 20px;" class="font-red font-bold w160">等待X位</span>
            </el-form-item>
            -->
          <el-form-item label="网店退票单号">
            <el-input class="w160" v-model="form.prid"/>
          </el-form-item>
          <el-form-item label="本地订单号">
            <el-input class="w160" v-model="form.localOrderId"/>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="所属网店" prop="shopCode">
            <el-select class="w160" v-model="form.shopCode">
              <el-option v-for="item in options.shop" :label="item.shopName" :value="item.shopNo" :key="item.shopNo"/>
            </el-select>
          </el-form-item>
          <el-form-item label="退票类型" prop="refundType">
            <el-select class="w160" v-model="form.refundType" clearable placeholder="请选择">
              <el-option v-for="item in options.platformRefundType" :label="item.value" :value="item.key"
                         :key="item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item label="网店出票单号" prop="issueBillId">
            <el-input class="w160" v-model="form.issueBillId"/>
          </el-form-item>
          <el-form-item label="提交日期">
            <el-date-picker format="yyyy-MM-dd HH:mm" type="datetime" v-model="form.rtTime" class="w200"/>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="退票事由">
            <el-autocomplete style="width: 1112px;"
                      :fetch-suggestions="(qs, cb) => cb(options.refundDesc)"
                      v-model="form.refundDesc"/>
          </el-form-item>
        </div>
      </el-card>

      <el-card class="card-bottom-spacing">
        <div slot="header" class="card-title">
          旅客信息
          <el-button type="primary" @click="onAddPassenger" size="mini" style="margin-left: 10px"><i class="fa fa-plus"></i> 新增旅客</el-button>
          <el-button type="primary" @click="onParsePassenger" size="mini"><i class="fa fa-edit"></i> 行程解析</el-button>
        </div>
        <el-table
          show-summary
          :summary-method="tableSummary"
          class="el-easy-ui-table"
          border
          :data="form.items">
          <el-table-column label="序号" width="50" type="index">
          </el-table-column>
          <el-table-column
            label="出发"
            min-width="50">
            <template slot-scope="scope">
              <el-form-item
                  :prop="'items[' + scope.$index + '].dPort'"
                  :rules="rules.dPort">
                <el-input v-model="scope.row.dPort" @input="v => $nextTick(() => {
                  scope.row.dPort = v.toUpperCase()
                })"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="到达"
            min-width="50">
            <template slot-scope="scope">
              <el-form-item
                  :prop="'items[' + scope.$index + '].aPort'"
                  :rules="rules.aPort">
                <el-input v-model="scope.row.aPort" @input="v => $nextTick(() => {
                  scope.row.aPort = v.toUpperCase()
                })"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="flight"
            label="航班"
            min-width="80">
            <template slot-scope="scope">
              <el-form-item
                  :prop="'items[' + scope.$index + '].flight'"
                  :rules="rules.flight">
                <el-input v-model="scope.row.flight" @input="v => $nextTick(() => {
                  scope.row.flight = v.toUpperCase()
                })"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="subClass"
            label="舱位"
            min-width="50">
            <template slot-scope="scope">
              <el-form-item
                  :prop="'items[' + scope.$index + '].subClass'"
                  :rules="rules.subClass">
                <el-input v-model="scope.row.subClass" @input="v => $nextTick(() => {
                  scope.row.subClass = v.toUpperCase()
                })"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="乘机日期"
            min-width="160">
            <template slot-scope="scope">
              <el-form-item
                  :prop="'items[' + scope.$index + '].takeOffTime'"
                  :rules="rules.takeOffTime">
                <el-date-picker format="yyyy-MM-dd HH:mm" type="datetime" v-model="scope.row.takeOffTime" class="w180"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="passengerName"
            label="姓名"
            min-width="100">
            <template slot-scope="scope">
              <el-form-item
                  :prop="'items[' + scope.$index + '].passengerName'"
                  :rules="rules.passengerName">
                <el-input v-model="scope.row.passengerName"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="票号" min-width="120">
            <template slot-scope="scope">
              <el-form-item prop="ticketNoAll">
                <el-input placeholder="xxx-xxxxxxxxxx" v-model="scope.row.ticketNoAll"
                          @input="onInputTicketNoAll(scope.row, $event)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="printPrice"
            label="票面价"
            min-width="80">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.printPrice" @input="onPassengerInput(scope.$index, 'printPrice', $event)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="cost"
            label="销售价"
            min-width="80">
            <template slot-scope="scope">
              <el-form-item
                :prop="'items[' + scope.$index + '].cost'"
                :rules="rules.cost">
                <el-input v-model="scope.row.cost" @input="onPassengerInput(scope.$index, 'cost', $event)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="税费+燃油"
            min-width="100">
            <template slot-scope="scope">
              <el-form-item style="display: inline-table"
                :prop="'items[' + scope.$index + '].tax'"
                            :rules="rules.tax">
                <el-input style="display: table-cell;width: 50%;" v-model="scope.row.tax"
                          @input="onPassengerInput(scope.$index, 'tax', $event)"/>
                <el-input style="display: table-cell;width: 50%;" v-model="scope.row.oilFee"
                          @input="onPassengerInput(scope.$index, 'oilFee', $event)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="refundFee"
            label="平台退票费"
            min-width="80">
            <template slot-scope="scope">
              <el-form-item
                :prop="'items[' + scope.$index + '].refundFee'"
                :rules="rules.refundFee">
                <el-input v-model="scope.row.refundFee" @input="onPassengerInput(scope.$index, 'refundFee', $event)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="payFlightAgency"
            label="平台退款"
            min-width="80">
            <template slot-scope="scope">
              <el-form-item
                :prop="'items[' + scope.$index + '].payFlightAgency'"
                :rules="rules.payFlightAgency">
                <el-input v-model="scope.row.payFlightAgency"
                          @input="onPassengerInput(scope.$index, 'payFlightAgency', $event)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="airlineRefund"
            label="航司退款"
            min-width="80">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.airlineRefund"
                          @input="onPassengerInput(scope.$index, 'airlineRefund', $event)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="利润"
            min-width="80">
            <template slot-scope="scope">
              {{((scope.row.airlineRefund !== '' && scope.row.airlineRefund !== null) ? ((+(scope.row.airlineRefund||0)) - (+(scope.row.payFlightAgency||0))) : 0) |
              money}}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            min-width="80">
            <template slot-scope="scope">
              <c-pop-button type="danger" size="mini" p-msg="确认删除？"
                            @click="$event => {form.items.splice(scope.$index ,1);$event.isLoading(false)}"><i class="fa fa-trash"></i> 删除
              </c-pop-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-card class="card-bottom-spacing">
        <div slot="header" class="card-title">
          航司退票信息
        </div>
        <div>
          <el-form-item label="出票渠道" prop="issueChannel">
            <el-select class="w200" v-model="form.issueChannel" clearable placeholder="请选择">
              <el-option v-for="item in options.issueChannel" :label="item.value" :value="item.key" :key="item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item label="退票类型">
            <el-select class="w200" v-model="form.airlineRefundType" clearable placeholder="请选择">
              <el-option v-for="item in options.refundType" :label="item.value" :value="item.key" :key="item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item label="支付方式" prop="payAccountType">
            <el-select class="w200" v-model="form.payAccountType" filterable>
              <el-option v-for="item in options.payAccountType" :label="item.value" :value="item.key" :key="item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item label="支付流水">
            <el-input class="w200" v-model="form.payNo"/>
          </el-form-item>
        </div>
        <div v-if="['BOP', 'BSP', 'B2B'].indexOf(form.issueChannel) > -1">
          <el-form-item label="小编码" prop="pnr" class="input-no-padding">
            <el-input class="w200" v-model="form.pnr"/>
          </el-form-item>
          <el-form-item label="大编码" prop="airlinePnr" class="input-no-padding">
            <el-input class="w200" v-model="form.airlinePnr" placeholder="   需自动B2B退票就填写"/>
          </el-form-item>
          <el-form-item label="预定Office号" prop="officeNo">
            <el-input class="w200" v-model="form.officeNo"/>
          </el-form-item>
          <el-form-item label="出票Office号" prop="issueOfficeNo">
            <el-select v-model="form.issueOfficeNo" class="w200" clearable>
              <el-option v-for="item in options.etermGroup" :key="item" :label="item" :value="item"/>
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="最晚取消PNR时间" prop="latestCancelPnrTime">
            <el-date-picker format="yyyy-MM-dd HH:mm" type="datetime" v-model="form.latestCancelPnrTime" class="w200"/>
            <easy-button type="primary" class="el-icon-refresh" size="mini" @click="onGetLatestCancelPnrTime"></easy-button>
          </el-form-item>
          <el-form-item label="航司订单号">
            <el-input v-model="form.airlineOrderId" placeholder="需自动B2B退票就填写" class="w200"/>
          </el-form-item>
          <el-form-item label="提交航司退票日期">
            <el-date-picker format="yyyy-MM-dd HH:mm" type="datetime" v-model="form.submitRefundTime" class="w200"/>
          </el-form-item>
          <el-form-item label="航司退款日期">
            <el-date-picker format="yyyy-MM-dd HH:mm" type="datetime" v-model="form.refundTime" class="w200"/>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="备注">
            <el-input
              v-model="form.remarks"
              type="textarea"
              style="width: 1250px;"
              :autosize="{ minRows: 2, maxRows: 8}"/>
          </el-form-item>
        </div>
      </el-card>
    </el-form>

    <el-card class="card-bottom-spacing">
      <div style="text-align: center">
        <easy-button type="primary" class="w120" @click="onSave">新增</easy-button>
        <el-button class="w120" @click="onClose">关闭</el-button>
      </div>
    </el-card>

    <el-dialog
      width="700px"
      :visible.sync="pnrDialog.visible"
      title="导入">
      <el-form ref="pnrDialogForm" size="mini" label-width="120px" :model="pnrDialog.form">
        <el-form-item label="导入类型">
          <el-radio-group v-model="pnrDialog.form.type">
            <el-radio label="1">PNR导入</el-radio>
            <el-radio label="2">PNR文本解析</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="PNR导入" v-if="pnrDialog.form.type === '1'" required prop="pnrCode" key="pnrCode"
                      :rules="rules.pnrCode">
          <el-input v-model="pnrDialog.form.pnrCode" placeholder="请输入小编码"/>
        </el-form-item>
        <el-form-item label="Office号" key="officeNo" v-if="pnrDialog.form.type === '1'">
          <el-select v-model="pnrDialog.form.officeNo" class="w200" clearable>
            <el-option v-for="item in options.etermGroup" :key="item" :label="item" :value="item"/>
          </el-select>
        </el-form-item>
        <el-form-item label="PNR文本解析" v-if="pnrDialog.form.type === '2'" required prop="pnrText" key="pnrText"
                      :rules="rules.pnrText">
          <el-input type="textarea"
                    v-model="pnrDialog.form.pnrText"
                    :autosize="{ minRows: 6, maxRows: 12}"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="pnrDialog.visible = false">取 消</el-button>
        <easy-button type="primary" @click="onPnrDialogOk">确 定</easy-button>
      </span>
    </el-dialog>

    <el-dialog
      width="800px"
      :visible.sync="tripDialog.visible"
      title="行程解析">
      <span>注：目前仅支持淘宝、同程、美团、去哪儿</span>
      <el-form ref="tripDialogForm"  label-width="120px" :model="tripDialog.form">

          <el-input type="textarea"
                    v-model="tripDialog.form.tripText"
                    :autosize="{ minRows: 6, maxRows: 18}"/>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="tripDialog.visible = false">取 消</el-button>
        <easy-button type="primary" @click="onTripDialogOk">确 定</easy-button>
      </span>
    </el-dialog>

  </l-content>
</template>

<script>
import tabManager from '@/eventBus/tabManager'
import Tab from '@/classes/Tab'

export default {
  name: 'OrderRefundDetail',
  props: {
    app: {
      type: Object,
      default () {
        return {
          extra: {}
        }
      }
    }
  },
  data () {
    return {
      now: new Date(),
      loading: false,
      options: {
        refundDesc: [],
        etermGroup: [],
        issueChannel: [],
        shop: [],
        refundType: [],
        rejectType: [],
        payAccountType: []
      },
      orderLog: [],
      form: {
        id: null,
        shopCode: this.$localStorage.get('orderRefund.shopCode'),
        orderId: null,
        prid: null,
        feeType: null,
        isForceAudited: null,
        refundServerFee: null,
        currency: null,
        conversionRate: null,
        createTime: null,
        isConfirm: null,
        audited: null,
        rtOper: null,
        rtTime: null,
        flightClass: null,
        prepayType: null,
        tickets: null,
        refundDesc: null,
        isRefund: null,
        takeOffTime: null,
        row: null,
        countNumber: null,
        urgency: null,
        refundReason: null,
        status: 'CONFIRMED',
        latestCancelPnrTime: null,
        cancelPnrTime: null,
        updateTime: null,
        updateUser: null,
        platform: null,
        issueBillId: null,
        issueChannel: 'B2B',
        pnr: null,
        airlinePnr: null,
        payType: null,
        payAccountType: null,
        payNo: null,
        officeNo: 'CSX510',
        issueOfficeNo: 'CSX510',
        refundTime: null,
        submitRefundTime: null,
        submitUser: null,
        airlineRefundType: null,
        refundType: '自愿',
        remarks: null,
        localOrderId: null,
        items: [{
          dPort: null,
          aPort: null,
          flight: null,
          subClass: null,
          takeOffTime: null,
          passengerName: null,
          ticketNoAll: null,
          printPrice: null,
          cost: null,
          tax: 50,
          oilFee: 30,
          refundFee: null,
          payFlightAgency: null,
          airlineRefundFee: null,
          airlineRefund: null
        }]
      },
      rules: {
        shopCode: this.$checkRules.orderRefundDetail.shopCode,
        refundType: this.$checkRules.orderRefundDetail.refundType,
        payFlightAgency: this.$checkRules.orderRefundDetail.payFlightAgency,
        issueChannel: this.$checkRules.orderRefundDetail.issueChannel,
        latestCancelPnrTime: this.$checkRules.orderRefundDetail.latestCancelPnrTime,
        pnrCode: this.$checkRules.orderRefundDetail.pnrCode,
        pnrText: this.$checkRules.orderRefundDetail.pnrText,
        pnr: this.$checkRules.notEmpty,
        officeNo: this.$checkRules.notEmpty,
        issueOfficeNo: this.$checkRules.notEmpty,
        issueBillId: this.$checkRules.notEmpty,
        dPort: this.$checkRules.notEmpty,
        aPort: this.$checkRules.notEmpty,
        flight: this.$checkRules.notEmpty,
        subClass: this.$checkRules.notEmpty,
        takeOffTime: this.$checkRules.notEmpty,
        passengerName: this.$checkRules.notEmpty,
        cost: this.$checkRules.notEmpty,
        tax: this.$checkRules.notEmpty,
        refundFee: this.$checkRules.notEmpty
      },
      pnrDialog: {
        visible: false,
        form: {
          type: '1',
          officeNo: null,
          pnrCode: '',
          pnrText: ''
        }
      },
      tripDialog: {
        visible: false,
        form: {
          type: '1',
          officeNo: null,
          pnrCode: '',
          tripText: ''
        }
      },
      regs: {
        TONGCHENG: [
          /(订单流水号：)?(\w+)\s(.*\n)+起飞时间：\s(.{19})/,
          /(.*)\S*(\w{6})\[(\w{1,2})\]\W(\d+\.?\d+)\s(\d+\.?\d+)\s(\d+\.?\d+)\s(\w{6})\s.*\s(\d{13})\s.*\s(\w+)/
        ],
        QUNAER: [
          /(\w+)\s?\n.*pnr：\s(\w{0,6}).*(\n.*)+操作\n\S*\s\S*\s\S*\s(\w{2})\s(\w{4})\s(\S+\n?\S*)\s(\S+)-(\S+)\s(\S{10}\s\S{5}).*\n.*\n.*¥(\d+\.?\d?)\s¥(\d+\.?\d?)\s¥(\d+\.?\d?)\/¥(\d+\.?\d?)\s/,
          /.*\s(\S*)\s+(\S+)\s+\S+\s+(\w+)\s.*\s(\w{3}-\w{10})/
        ],
        MEITUAN: [
          /(\w+).*\n.*成人PNR：\s?(\w{0,6})儿童PNR：\s?(\w{0,6})\s(.*\n)+.*经停\n(\w{6})\n(.{16})\s(\S+)\s?\n.{16}\s(\S+)\s?\n(.*\n)+成人：(\w+)\n儿童：(\w{0,2})/,
          /(\S+)\s￥(\d+\.?\d?)\s￥(\d+\.?\d?)\s￥(\d+\.?\d?)\/￥(\d+\.?\d?)/,
          /\s(.*)(身份证)|(护照)/,
          /票号：\s?(\S+)\s/
        ],
        TAOBAO: [
          /(\w+)\s+-\s+(\w+)\s+.*\s+(\w{6})\s+\/(.*)/
        ]
      }
    }
  },
  watch: {
    'form.issueChannel' () {
      this.$refs['form'].clearValidate(['pnr'])
    }
  },
  created () {
    this.$dateUtils.getNow().then(now => {
      this.now = now
    })
    this.loadOptions()
  },
  methods: {
    tableSummary (param) {
      const {columns, data} = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '汇总'
          return
        }
        if ((index >= 8 && index <= 13) && index !== 10) {
          const values = data.map(item => Number(item[column.property] || 0))
          const sum = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = this.$options.filters.money(sum)
        } else if (index === 10) {
          const values1 = data.map(item => Number(item.tax || 0))
          const values2 = data.map(item => Number(item.oilFee || 0))
          const sum = [...values1, ...values2].reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = this.$options.filters.money(sum)
        } else if (index === 14) {
          // 航司退款
          const values1 = data.map(item => Number(item.airlineRefund || 0))
          // 平台退款
          const values2 = data.map(item => -Number(((item.airlineRefund === null || item.airlineRefund === '' || item.airlineRefund === undefined) ? 0 : item.payFlightAgency) || 0))
          const sum = [...values1, ...values2].reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = this.$options.filters.money(sum)
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    loadOptions () {
      this.$service.options.getIssueChannel().then(res => {
        this.options.issueChannel = res.data
      })
      this.$service.order.queryAirOnlineShopList().then(res => {
        this.options.shop = res.data
      })
      this.$service.options.getRefundType().then(res => {
        this.options.refundType = res.data
      })
      this.$service.options.getRefundDesc().then(res => {
        this.options.refundDesc = res.data
      })
      // this.$service.options.getPayType().then(res => {
      //   this.options.payType = res.data
      // })
      this.$service.options.getYeePayAccountType().then(res => {
        this.options.payAccountType = res.data
      })
      this.$service.eterm.queryAllGroupList().then(res => {
        this.options.etermGroup = res.data
      })
      this.options.platformRefundType = [
        {'key': '自愿', 'value': '自愿'},
        {'key': '非自愿', 'value': '非自愿'}
      ]
    },
    onImport () {
      this.pnrDialog.visible = true
    },
    onPnrDialogOk (done) {
      this.$refs['pnrDialogForm'].validate(valid => {
        if (valid) {
          this.$service.airRefund.getRefundInfoByPnr(this.pnrDialog.form).then(res => {
            Object.assign(this.form, res.data)
            this.pnrDialog.visible = false
            this.form.items.forEach(item => {
              item.tax = item.tax || 50
              item.oilFee = item.oilFee || 10
            })
            this.form.issueChannel = this.form.issueChannel || 'B2B'
            this.form.officeNo = this.form.officeNo || 'CSX510'
            this.form.issueOfficeNo = this.form.issueOfficeNo || 'CSX510'
          }).finally(done)
        } else {
          done()
        }
      })
    },
    onTripDialogOk (done) {
      var _this = this
      if (_this.tripDialog.form.tripText == null || _this.tripDialog.form.tripText === '') {
        this.$alert('请粘贴行程信息', '提示')
        done()
        return
      }
      var arr
      var tripInfo
      var passengers
      try {
        if (this.form.shopCode.indexOf('TC') > -1) { /* 同程 */
          arr = this.tripDialog.form.tripText.split('证件号\n')
          var takeOffTime = arr[0].match(this.regs.TONGCHENG[0])
          _this.form.issueBillId = takeOffTime[2]
          passengers = arr[1].trim().split('\n')
          if (passengers != null && passengers.length > 0) {
            _this.form.items = []
            for (var k = 0; k < passengers.length; k++) {
              var passenger = passengers[k]
              var passengerGroup = passenger.match(_this.regs.TONGCHENG[1])
              _this.form.pnr = passengerGroup[7]
              _this.form.items.push({
                dPort: null,
                aPort: null,
                flight: passengerGroup[2],
                subClass: passengerGroup[3],
                takeOffTime: new Date(takeOffTime[4]),
                passengerName: passengerGroup[1],
                ticketNoAll: passengerGroup[8],
                printPrice: null,
                cost: passengerGroup[4],
                tax: 50,
                oilFee: 30,
                refundFee: passengerGroup[5],
                payFlightAgency: passengerGroup[6],
                airlineRefundFee: null,
                airlineRefund: null
              })
            }
          }
        } else if (this.form.shopCode.indexOf('QN') > -1) { /* 去哪儿 */
          arr = this.tripDialog.form.tripText.split('保险\n')
          tripInfo = arr[0].match(this.regs.QUNAER[0])
          _this.form.issueBillId = tripInfo[1]
          _this.form.pnr = tripInfo[2]

          /* 计算仓位，如果都是成人仓位就一样，有儿童的话就有多个仓位 */
          // 单个仓位
          var subClass = null
          // 多个仓位
          var subClassObj = {}
          var subClassArr = tripInfo[6].split('\n')
          if (subClassArr.length === 1) {
            subClass = tripInfo[6]
          } else {
            subClassArr.forEach(function (scs) {
              var arr = scs.split('：')
              subClassObj[arr[0]] = arr[1]
            })
          }

          passengers = arr[1].trim().split('\n')
          if (passengers != null && passengers.length > 0) {
            _this.form.items = []
            passengers.forEach(function (passenger) {
              if (passenger !== '') {
                var passengerGroup = passenger.match(_this.regs.QUNAER[1])
                var passengerType = passengerGroup[1].trim()
                _this.form.items.push({
                  dPort: tripInfo[7],
                  aPort: tripInfo[8],
                  flight: tripInfo[4] + tripInfo[5],
                  subClass: subClass === null ? subClassObj[passengerType] : subClass,
                  takeOffTime: new Date(tripInfo[9]),
                  passengerName: passengerGroup[2],
                  ticketNoAll: passengerGroup[4],
                  printPrice: tripInfo[11],
                  cost: tripInfo[10],
                  tax: tripInfo[12],
                  oilFee: tripInfo[13],
                  refundFee: null,
                  payFlightAgency: null,
                  airlineRefundFee: null,
                  airlineRefund: null
                })
              }
            })
          }
        } else if (this.form.shopCode.indexOf('KX') > -1) { /* 美团酷讯 */
          arr = this.tripDialog.form.tripText.split('总价\n')
          tripInfo = arr[0].match(this.regs.MEITUAN[0])
          _this.form.issueBillId = tripInfo[1]
          _this.form.pnr = tripInfo[2]
          var childPnr = tripInfo[3]
          if (childPnr != null && childPnr !== '') {
            _this.form.remarks = '儿童PNR:' + childPnr
          }

          var arr2 = arr[1].split('乘机人数')
          var priceInfo = arr2[0].match(this.regs.MEITUAN[1])
          var passengerInfo = arr2[1].split('\n')
          /*
          * 第二部分为
          * ：2人
            成人： 马小霁身份证：622429199504270251
            第1程票号：876-2116216186 校验成功
            成人： 韩月身份证：652927199711242720
            第1程票号：876-2116216185 校验成功
          * */
          if (passengerInfo.length > 1) {
            _this.form.items = []
          }
          for (var i = 0; i < (passengerInfo.length - 1) / 2; i++) {
            var nameInfo = passengerInfo[i * 2 + 1].match(this.regs.MEITUAN[2])
            var ticketInfo = passengerInfo[i * 2 + 2].match(this.regs.MEITUAN[3])
            _this.form.items.push({
              dPort: tripInfo[7],
              aPort: tripInfo[8],
              flight: tripInfo[5],
              subClass: tripInfo[10],
              takeOffTime: new Date(tripInfo[6]),
              passengerName: nameInfo[1],
              ticketNoAll: ticketInfo[1],
              printPrice: priceInfo[3],
              cost: priceInfo[2],
              tax: priceInfo[4],
              oilFee: priceInfo[5],
              refundFee: null,
              payFlightAgency: null,
              airlineRefundFee: null,
              airlineRefund: null
            })
          }
        } else if (this.form.shopCode.indexOf('TB') > -1) { /* 淘宝 */
          arr = this.tripDialog.form.tripText.split('\n')
          console.log(arr)
          if (arr.length > 10) {
            _this.form.items = []
          }
          var boundary = this.tripDialog.form.tripText.indexOf('补退') > -1 ? 12 : 11
          for (var j = 0; j < arr.length / boundary; j++) {
            tripInfo = arr[1].match(_this.regs.TAOBAO[0])
            priceInfo = arr[3].trim().split('\t')
            var taxs = arr[4].split('/')
            _this.form.items.push({
              dPort: tripInfo[1],
              aPort: tripInfo[2],
              flight: tripInfo[3],
              subClass: null,
              takeOffTime: new Date(tripInfo[4]),
              passengerName: arr[j * boundary],
              ticketNoAll: null,
              printPrice: priceInfo[0],
              cost: priceInfo[3],
              tax: taxs[0],
              oilFee: taxs[1],
              refundFee: arr[6],
              payFlightAgency: null,
              airlineRefundFee: null,
              airlineRefund: null
            })
          }
        }
      } catch (e) {
        console.log(e)
      }
      _this.tripDialog.visible = false
      done()
    },
    getSubClass (str, type) {

    },
    onSave (done) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let tip = '是否确认新增？'
          const latestCancelPnrTime = new Date(this.form.latestCancelPnrTime)
          const remaining = Math.round((latestCancelPnrTime.getTime() - this.now.getTime()) / 1000 / 60)
          if (remaining < 0) {
            tip = '设置的最晚取消pnr时间小于当前时间，请确认是否新增？'
          } else if (remaining <= 15) {
            tip = '设置的最晚取消pnr时间离现在只差' + remaining + '分钟了，请确认是否新增？'
          }
          this.$confirm(tip, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$localStorage.set('orderRefund.shopCode', this.form.shopCode)
            this.$service.airRefund.save(this.form).then(res => {
              this.app.close()
              var name = '退票单'
              if (res.data.prid != null) {
                name = '退票单-' + res.data.prid
              }
              tabManager.addTab(new Tab({
                key: 'airOrderManage.orderRefundDetail',
                name: name,
                extra: {refundId: res.data.id}
              }))
            }).finally(done)
          }).catch(done)
        } else {
          this.$alert('校验未通过', '提示')
          done()
        }
      })
    },
    onClose () {
      this.app.close()
    },
    onAddPassenger () {
      if (this.form.items.length > 0) {
        var item0 = Object.assign({}, this.form.items[0])
        item0.passengerName = null
        item0.ticketNoAll = null
        item0.id = null
        this.form.items.push(item0)
      } else {
        this.form.items.push({
          dPort: null,
          aPort: null,
          flight: null,
          subClass: null,
          takeOffTime: null,
          passengerName: null,
          ticketNoAll: null,
          printPrice: null,
          cost: null,
          tax: 50,
          oilFee: 30,
          refundFee: null,
          payFlightAgency: null,
          airlineRefundFee: null,
          airlineRefund: null
        })
      }
    },
    onParsePassenger () {
      if (this.form.shopCode == null) {
        this.$alert('请先选择网店', '提示')
      } else {
        this.tripDialog.visible = true
      }
    },
    onInputTicketNoAll (row, v) {
      const str = v.replace(/-/g, '')
      if (str.length > 3) {
        const no1 = str.substring(0, 3)
        const no2 = str.substring(3)
        this.$nextTick(() => {
          row.ticketNoAll = no1 + '-' + no2
        })
      }
    },
    calcCost (idx, key, v) {
      if (v !== null && v !== '') {
        const item = this.form.items[idx]
        const total = Number(item.cost || 0) + Number(item.tax || 0) + Number(item.oilFee || 0)
        if (key === 'payFlightAgency') {
          item.refundFee = '' + Number((total - Number(v)).toFixed(2))
        } else if (key === 'refundFee') {
          item.payFlightAgency = '' + Number((total - Number(v)).toFixed(2))
        }
      }
    },
    onPassengerInput (idx, key, v) {
      if (idx === 0) {
        this.$nextTick(() => {
          this.form.items.forEach((item, index) => {
            item[key] = v
            this.calcCost(index, key, v)
          })
        })
      } else {
        this.calcCost(idx, key, v)
      }
    },
    onGetLatestCancelPnrTime (done) {
      if (this.form.items === null || this.form.items.length === 0) {
        this.$alert('请先填写乘客信息', '提示')
        done()
      } else {
        if (this.form.items[0].flight === null || this.form.items[0].flight === '' || this.form.items[0].flight.length < 2 ||
            this.form.items[0].subClass === null || this.form.items[0].subClass === '' || this.form.items[0].takeOffTime === null || this.form.items[0].takeOffTime === '') {
          this.$alert('请填写第一位乘客的航班号、舱位、起飞时间', '提示')
          done()
        } else {
          this.$service.airRefund.getLatestCancelPnrTime(this.form).then(res => {
            if (res.code === '0000' && res.data != null) {
              this.form.latestCancelPnrTime = res.data
            }
          }).catch(done).finally(done)
        }
      }
    }
  }
}
</script>

<style></style>
